package com.its.cloud.controller;

import com.its.cloud.entity.ResultBean;
import com.its.cloud.service.PaymentFeignService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.naming.Name;
import java.util.concurrent.TimeUnit;

/**
 * @author huguangjun
 * @className OrderController
 * @date 2021/1/8
 * @desc 10:57
 */
@RestController
// 全局配置豪猪哥断路，高版本的失效
//@DefaultProperties(defaultFallback = "getById_Global")
public class OrderController {

    @Resource
    private PaymentFeignService paymentFeignService;


    @GetMapping("/consumer/payment/get/{id}")
//    @HystrixCommand(fallbackMethod = "getById_Timeout",commandProperties = {
//            // 断路器设置此方法为XX秒
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "20000")
//    })
    public ResultBean get(@PathVariable("id") Long id) {
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paymentFeignService.get(id);
    }


    /**
     * 豪猪哥的断路器
     *
     * @param id
     * @return
     */
    @GetMapping("/consumer/hzg/get/{id}")
    // 单一降级配置
//    @HystrixCommand(fallbackMethod = "getById_Timeout",commandProperties = {
//            // 断路器设置此方法为2秒
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000")
//    })
    public ResultBean getById(@PathVariable("id") Long id) {
        try {
            // 超时3秒
            TimeUnit.SECONDS.sleep(5);
            //Thread.sleep(5000);

            // exception
            // 低版本的2.2.1，只要出现了异常也会出现服务降级，但在此高版本只有超时会降级处理
            //int i = 1/0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paymentFeignService.get(id);
    }

    /**
     * 测试error的降级
     * ok
     * @param id
     * @return
     */
    @GetMapping("/consumer/payment/error/{id}")
    @HystrixCommand(fallbackMethod = "getById_Timeout",commandProperties = {
            // 断路器设置此方法为2秒
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000")
    })
    public ResultBean getError(@PathVariable("id") Long id) {
        int i = 1/0;
        return paymentFeignService.get(id);
    }

    public ResultBean getById_Timeout(Long id) {
        return new ResultBean("超时了" + id);
    }


    public ResultBean getById_Global() {
        return new ResultBean("全局的降级：");
    }
}
